package buildervalidator

import (
	"errors"
	"fmt"
	"yunj/pkg/yunj/util"

	"github.com/worklz/go-validate"
)

type Form struct {
	validate.Validator
}

func (v *Form) DefineRules() map[string]interface{} {
	return map[string]interface{}{
		"builder_id":         "required",
		"builder_async_type": "required|in:submit",
	}
}

func (v *Form) DefineTitles() map[string]string {
	return map[string]string{
		"builder_id" + ".required":         "访问错误",
		"builder_async_type" + ".required": "builder_async_type" + "参数缺失",
		"builder_async_type" + ".in":       "builder_async_type" + "参数错误",
	}
}

func (v *Form) DefineScenes() map[string][]string {
	return map[string][]string{
		"AsyncRequest": {"builder_id", "builder_async_type"},
	}
}

func (v *Form) HandleDatas(datas map[string]interface{}, scene string) (err error) {
	if scene == "AsyncRequest" {
		typ := datas["builder_async_type"]
		switch typ {
		case "submit":
			err = v.HandleDatasBySubmit(datas)
		}
	}
	return
}

func (v *Form) HandleDatasBySubmit(datas map[string]interface{}) (err error) {
	data, exists := datas["data"]
	if !exists {
		err = errors.New("data参数缺失")
		return
	}
	dataStr, ok := data.(string)
	if !ok {
		err = errors.New("data参数异常")
		return
	}
	dataMap, err := util.JsonTo[map[string]interface{}](dataStr)
	if err != nil {
		return fmt.Errorf("data参数类型错误！%v", err)
	}
	datas["data"] = dataMap
	return
}
